pipeline {
    agent any
    triggers {
        cron('H 2 * * *') // 每天凌晨 4 点触发
    }
    parameters {
        choice(
            name: 'BUILD_TYPE',
            choices: ['All', 'NQ10-AI', 'NQ10', 'NC1-10','NC2-10','NQ36', 'NQ16-AI'],
            description: '选择要构建的型号（选择"All"将构建所有型号）'
        )
        string(name: 'VERSION', defaultValue: '13', description: '输入版本号')
    }
    
    environment {
        REMOTE_HOST = '192.168.190.34'
        REMOTE_USER = 'veepai'
        REMOTE_PASSWORD = 'veepai'
        REMOTE_DIR = '/data/share/wangrui/auto'
        UPLOAD_DIR = '/mnt/firmware_Submit_Test/nvr_build_version'
        NEW_DATA_DIR = '/tmp/new_firmware_data'
    }
    
    stages {
        stage('SSH and Build') {
            steps {
                script {
                    def remote = [:]
                    remote.name = 'build-server'
                    remote.host = env.REMOTE_HOST
                    remote.user = env.REMOTE_USER
                    remote.password = env.REMOTE_PASSWORD
                    remote.allowAnyHosts = true
                    
                    sshCommand remote: remote, command: """
                        set -e
                        echo "开始构建过程..."
                        cd ${env.REMOTE_DIR}
                        BUILD_PATH=\$(pwd)
                        BUILD_NVR_VER='${params.VERSION}'
                        export BUILD_NVR_VER=\$BUILD_NVR_VER
                        VPNVR_PATH=\$BUILD_PATH/vpnvr
                        NQ_PATH=\$BUILD_PATH/N*
                        VPNVR_BUILD_PATH=\$BUILD_PATH/vpnvr/board/product/ingenic_a1/build
                        OUT_PATH=\$VPNVR_BUILD_PATH/out/bin
                        DATE=\$(date '+%Y%m%d_%H%M%S')
                        
                        rm -rf \$VPNVR_PATH
                        rm -rf \$NQ_PATH
                        rm -rf \$BUILD_PATH/*.bin
                        
                        git clone /data/git/vpnvr
                        if [ \$? -ne 0 ]; then
                            echo "Git clone 失败"
                            exit 1
                        fi
                        
                        echo "Git clone 成功"
                        cd \$VPNVR_BUILD_PATH
                        
                        if [ '${params.BUILD_TYPE}' = 'All' ]; then
                            echo "-----------构建所有型号-------------"
                            ./auto_build.sh "NQ10-AI"
                            if [ \$? -eq 0 ]; then
                                echo "NQ10-AI 构建成功"
                                cp -rf \$OUT_PATH \$BUILD_PATH
                                mv \$BUILD_PATH/bin \$BUILD_PATH/NQ10_AI_\$DATE
                            else
                                echo "NQ10-AI 构建失败"
                                exit 1
                            fi
                            
                            ./auto_build.sh "NQ16-AI"
                            if [ \$? -eq 0 ]; then
                                echo "NQ16-AI 构建成功"
                                cp -rf \$OUT_PATH \$BUILD_PATH
                                mv \$BUILD_PATH/bin \$BUILD_PATH/NQ16_AI_\$DATE
                            else
                                echo "NQ16-AI 构建失败"
                                exit 1
                            fi
                            
                            ./auto_build.sh "NC1-10"
                            if [ \$? -eq 0 ]; then
                                echo "build nc1-10 success"
                                cp -rf \$OUT_PATH \$BUILD_PATH
                                mv \$BUILD_PATH/bin \$BUILD_PATH/NC1-10_\$DATE
                            else
                                echo "NC1-10 构建失败"
                                exit 1
                            fi
                            
                             ./auto_build.sh "NC2-10"
                            if [ \$? -eq 0 ]; then
                                echo "build nc2-10 success"
                                cp -rf \$OUT_PATH \$BUILD_PATH
                                mv \$BUILD_PATH/bin \$BUILD_PATH/NC2-10_\$DATE
                            else
                                echo "NC2-10 构建失败"
                                exit 1
                            fi
                            
                            ./auto_build.sh "NQ36"
                            if [ \$? -eq 0 ]; then
                                echo "build NQ36-ai success"
                                cp -rf \$OUT_PATH \$BUILD_PATH
                                mv \$BUILD_PATH/bin \$BUILD_PATH/NQ36_\$DATE
                            else
                                echo "NQ36 构建失败"
                                exit 1
                            fi
                        else
                            echo "----------构建 ${params.BUILD_TYPE}----------"
                            ./auto_build.sh '${params.BUILD_TYPE}'
                            
                            if [ \$? -eq 0 ]; then
                                echo "${params.BUILD_TYPE} 构建成功"
                                cp -rf \$OUT_PATH \$BUILD_PATH
                                mv \$BUILD_PATH/bin \$BUILD_PATH/${params.BUILD_TYPE}_\$DATE
                            else
                                echo "构建失败"
                                exit 1
                            fi
                        fi
                        
                        echo "构建过程成功完成"
                    """
                }
            }
        }
        
        stage('Prepare Environment') {
            steps {
                sh '''
                    echo "开始准备环境"
                    echo "当前用户: $(whoami)"
                    echo "当前目录: $(pwd)"
                    echo "系统信息:"
                    uname -a
                    echo "检查压缩工具:"
                    which tar || (echo "正在安装 tar..." && sudo apt-get update && sudo apt-get install -y tar)
                    echo "检查nohup工具:"
                    which nohup || (echo "正在安装 coreutils..." && sudo apt-get update && sudo apt-get install -y coreutils)
                    which tar
                    which nohup
                '''
            }
        }
        stage('Copy New Firmware to Jenkins') {
            steps {
                script {
                    def remote = [:]
                    remote.name = 'build-server'
                    remote.host = env.REMOTE_HOST
                    remote.user = env.REMOTE_USER
                    remote.password = env.REMOTE_PASSWORD
                    remote.allowAnyHosts = true
                    
                    sshCommand remote: remote, command: """
                        cd ${env.REMOTE_DIR}
                        echo "检查NQ10_AI目录内容："
                        ls -la NQ10_AI_*
                        echo "检查文件权限："
                        stat NQ10_AI_*/*
                        echo "当前目录内容："
                        ls -la
                        
                        echo "查找N*目录："
                        NEW_DIRS=\$(find . -maxdepth 1 -type d -name 'N*')
                        echo "找到的目录：\$NEW_DIRS"
                        
                        # 先删除旧数据
                        rm -rf /tmp/new_firmware.tar.gz
                        if [ -n "\$NEW_DIRS" ]; then
                            echo "开始打包以下目录:"
                            echo "\$NEW_DIRS"
                            tar -czvf /tmp/new_firmware.tar.gz \$NEW_DIRS || (echo "打包失败，错误代码：\$?"; exit 1)
                            echo "打包完成，检查tar文件内容："
                            tar -tvf /tmp/new_firmware.tar.gz
                        else
                            echo "未找到新的固件目录"
                            exit 1
                        fi
                    """
                    
                    // 从远程服务器获取新的 tar 文件
                    sshGet remote: remote, from: '/tmp/new_firmware.tar.gz', into: '/tmp/new_firmware.tar.gz', override: true
                    
                    // 解压新固件数据到临时目录
                    sh """
                        echo "解压新固件文件"
                        sudo mkdir -p ${env.NEW_DATA_DIR}
                        ls -R ${env.NEW_DATA_DIR}
                        sudo tar -xzvf /tmp/new_firmware.tar.gz -C ${env.NEW_DATA_DIR}
                        sudo rm /tmp/new_firmware.tar.gz
                        sudo chmod -R 755 ${env.NEW_DATA_DIR}
                        echo "新固件数据内容:"
                        ls -R ${env.NEW_DATA_DIR}
                    """
                }
            }
        }
        
        stage('Archive New Artifacts') {
            steps {
                script {
                    def currentDate = new Date().format('yyyy-MM-dd')
                    
                    // Create a directory to store individual firmware files
                    sh """
                        echo "显示NEW_DATA_DIR内容："
                        ls -R ${env.NEW_DATA_DIR}
                        
                        echo "创建firmware_artifacts目录"
                        mkdir -p ${WORKSPACE}/firmware_artifacts
                        
                        echo "复制固件文件："
                        find ${env.NEW_DATA_DIR} -name 'N*.bin' -type f -exec ls -l {} \\;
                        find ${env.NEW_DATA_DIR} -name 'N*.bin' -type f -exec cp -v {} ${WORKSPACE}/firmware_artifacts/ \\;
                        
                        echo "firmware_artifacts目录内容："
                        ls -l ${WORKSPACE}/firmware_artifacts/
                    """

                    // Copy and rename firmware files
                    sh """
                        find ${env.NEW_DATA_DIR} -name 'N*.bin' -exec cp {} ${WORKSPACE}/firmware_artifacts/ \\;
                        cd ${WORKSPACE}/firmware_artifacts
                    """

                    // Archive individual firmware files
                    archiveArtifacts artifacts: 'firmware_artifacts/*.bin', fingerprint: true

                    // Create and archive the full TAR file
                    def tarFileName = "NVR_${currentDate}_full.tar.gz"
                    sh """
                        cd ${env.NEW_DATA_DIR}
                        tar -czvf ${WORKSPACE}/${tarFileName} .
                        sudo chown jenkins:jenkins ${WORKSPACE}/${tarFileName}
                    """
                    archiveArtifacts artifacts: "${tarFileName}", fingerprint: true

                    // Copy files to UPLOAD_DIR and clean up
                    sh """
                        sudo cp -R ${env.NEW_DATA_DIR}/* ${env.UPLOAD_DIR}/
                        rm -rf ${WORKSPACE}/firmware_artifacts
                        rm -f ${WORKSPACE}/${tarFileName}
                        sudo rm -rf ${env.NEW_DATA_DIR}
                    """
                }
            }
        }
    }
    
   post {
        failure {
            echo """=== 构建失败 ===
    构建信息:
    - 构建类型: ${params.BUILD_TYPE}
    - 版本号: ${params.VERSION}
    - 工作目录: ${WORKSPACE}
    请检查以上阶段的日志获取详细错误信息。
    """
        }
        success {
            echo """=== 构建成功 ===
    构建信息:
    - 构建类型: ${params.BUILD_TYPE}
    - 版本号: ${params.VERSION}
    - 工作目录: ${WORKSPACE}
    """
        }
        always {
            echo "构建完成时间: ${new Date()}"
        }
    }
}